﻿Imports System.Net
Imports System.IO

Public Class frmMain

    Dim viewerList As New List(Of Integer)
    Dim clock As New Integer
    Dim totalTime As Integer

    Private Sub tmrInterval_Tick(sender As Object, e As EventArgs) Handles tmrInterval.Tick
        ClockTick()
        
    End Sub

    Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
        tmrInterval.Interval = Integer.Parse(txtInterval.Text) * 1000
        viewerList.Clear()
        tmrInterval.Start()
        Timer1.Start()
        Timer2.Start()
        totalTime = 0
        clock = 0
        ClockTick()
    End Sub

    Private Sub ClockTick()
        Dim sURL As String
        Dim wrGETURL As WebRequest
        Dim objStream As Stream
        sURL = "http://api.justin.tv/api/stream/list.json?channel=" + txtStreamer.Text

        wrGETURL = WebRequest.Create(sURL)

        objStream = wrGETURL.GetResponse.GetResponseStream()

        Dim objReader As New StreamReader(objStream)
        Dim sLine As String = ""
        Dim i As Integer = 0

        sLine = objReader.ReadLine
        ' between "channel_count": and ,

        If sLine.Length > 5 Then
            Dim sCount As String = ""
            i = sLine.IndexOf(",", sLine.IndexOf("channel_count")) - (sLine.IndexOf("channel_count") + 15)

            txtViewers.Text += sLine.Substring(sLine.IndexOf("channel_count") + 15, i) + vbCrLf
            viewerList.Add(Integer.Parse(sLine.Substring(sLine.IndexOf("channel_count") + 15, i)))
        End If

        clock = 0
    End Sub

    Private Sub btnAvgHighest_Click(sender As Object, e As EventArgs) Handles btnAvgHighest.Click
        tmrInterval.Stop()
        Timer1.Stop()
        Timer2.Stop()

        Dim total As Integer = 0
        Dim highest As Integer = 0

        For Each i As Integer In viewerList
            If (i > highest) Then
                highest = i
            End If

            total = total + i
        Next

        Dim average As Integer = total / viewerList.Count

        txtAvgHighest.Text = average.ToString() + "/" + highest.ToString() + "/" + totalTime.ToString()
    End Sub

    Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
        txtViewers.Text = ""
        viewerList.Clear()
    End Sub

    Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        tmrInterval.Stop()
        Timer1.Stop()

    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        clock = clock + 1
        lblClock.Text = clock.ToString()
    End Sub

    Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
        totalTime = totalTime + 1
    End Sub
End Class
